package com.hs.permission.filter;


import com.hs.jwt.JwtTemplate;
import com.hs.permission.service.SecurityUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Token过滤器.
 * 考虑到分布式代码环境，请求大多来源于其他项目或者微服务，所以我们需要通过过滤器来处理请求，下面是过滤器的代码
 * OncePerRequestFilter顾名思义，他能够确保在一次请求只通过一次filter，而不需要重复执行.
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private SecurityUserService securityUserService;

    private JwtTemplate jwtTokenUtil;

    @Autowired
    public JwtAuthenticationTokenFilter(
            SecurityUserService securityUserService, JwtTemplate jwtTokenUtil) {
        this.securityUserService = securityUserService;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null) {
            String authToken = authHeader;
            String username = (String) jwtTokenUtil.parseToken(authToken,"username");
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = this.securityUserService.loadUserByUsername(username);
                if (jwtTokenUtil.verify(authToken)) {
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request, response);
    }

}